package com.rightsidetech.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.PageRequest;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.exception.BizException;
import com.rightsidetech.commom.utils.AppVersionUnit;
import com.rightsidetech.system.dtos.request.AppUpdateReq;
import com.rightsidetech.system.dtos.response.AppVersionResp;
import com.rightsidetech.system.dtos.response.SysAppVersionResp;
import com.rightsidetech.system.entity.SysAppVersion;
import com.rightsidetech.system.entity.SysUserLoginInfo;
import com.rightsidetech.system.mapper.SysAppVersionMapper;
import com.rightsidetech.system.mapper.SysUserLoginInfoMapper;
import com.rightsidetech.system.service.AppUpdateService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @Author: yhr
 * @Date: 2021-11-09 14:21
 */
@Service("appUpdateServiceImpl")
public class AppUpdateServiceImpl implements AppUpdateService {
    @Resource
    private SysAppVersionMapper sysAppVersionMapper;
    @Resource
    private SysUserLoginInfoMapper sysUserLoginInfoMapper;

    @Override
    public ResponseData<PageInfo<SysAppVersionResp>> versionPage(PageRequest req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<SysAppVersionResp> list = sysAppVersionMapper.page();
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData insertAppDate(AppUpdateReq updateReq, Long loginInfoId, String type) throws BizException {
        boolean isMatch = Pattern.matches("\\d+(\\.\\d+)(\\.\\d+)", updateReq.getVersion());
        if(!isMatch){
            return ResponseData.fail("版本号格式不合法");
        }
        SysAppVersion version = sysAppVersionMapper.checkAppVersion(updateReq);
        if (!ObjectUtils.isEmpty(version)){
            if ("insert".equals(type)){
                if (version.getId() > 0){
                    return ResponseData.fail("版本号不能重复");
                }
            }
            if ("update".equals(type)){
                if (!updateReq.getId().equals(version.getId())){
                    return ResponseData.fail("版本号不能重复");
                }
            }
        }
        SysAppVersion sysAppVersion = new SysAppVersion();
        sysAppVersion.setAppOs(updateReq.getAppOs());
        sysAppVersion.setVersion(updateReq.getVersion());
        sysAppVersion.setDescription(updateReq.getDescription());
        sysAppVersion.setAppType(updateReq.getAppType());
        sysAppVersion.setBugType(updateReq.getBugType());
        if (!ObjectUtils.isEmpty(updateReq.getUrl())){
            sysAppVersion.setUrl(updateReq.getUrl());
        }
        if (!ObjectUtils.isEmpty(updateReq.getMd5())){
            sysAppVersion.setMd5(updateReq.getMd5());
        }
        SysUserLoginInfo info = sysUserLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(info)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if ("insert".equals(type)){
            sysAppVersion.setCreateName(info.getLoginName());
            sysAppVersion.setCreatedAt(new Date());
            sysAppVersionMapper.insertSelective(sysAppVersion);
        }
        if ("update".equals(type)){
            sysAppVersion.setId(updateReq.getId());
            sysAppVersion.setUpdateName(info.getLoginName());
            sysAppVersion.setUpdatedAt(new Date());
            sysAppVersionMapper.updateByPrimaryKeySelective(sysAppVersion);
        }
        return ResponseData.success();
    }

    @Override
    public SysAppVersion selectByPrimaryKey(Long id) {
        return sysAppVersionMapper.selectByPrimaryKey(id);
    }

    @Override
    public ResponseData<AppVersionResp> versionDate(String appVersion, Byte appOs, Byte appType) throws Exception {
        //获取最新版本
        SysAppVersion optionalMaxVersion = sysAppVersionMapper.versionMaxDate(appOs, appType);
        if(StringUtils.isEmpty(optionalMaxVersion)){
            return ResponseData.fail("暂无升级版本");
        }

        if (AppVersionUnit.compareVersion(appVersion, optionalMaxVersion.getVersion()) >= 0){
            return ResponseData.fail(CodeIdEnum.UPDATED_VERSION);
        }

        AppVersionResp appVersionResp = null;
        SysAppVersion mustMaxVersion = null;
        if (optionalMaxVersion.getBugType() == 2){
            appVersionResp = new AppVersionResp(optionalMaxVersion.getUrl(), optionalMaxVersion.getVersion(), optionalMaxVersion.getMd5(), optionalMaxVersion.getDescription(), (byte) 2);
            return ResponseData.success(appVersionResp);
        }else {
            //获取强制最新版本
            mustMaxVersion = sysAppVersionMapper.versionDate(appOs, appType, (byte) 2);
        }

        if(!ObjectUtils.isEmpty(optionalMaxVersion) && !ObjectUtils.isEmpty(mustMaxVersion)){
            String optionalMaxVersionStr = optionalMaxVersion.getVersion();
            String mustMaxVersionStr = mustMaxVersion.getVersion();

            //比较版本号的大小,前者大则返回一个正数,后者大返回一个负数,相等则返回0
            int result1 = AppVersionUnit.compareVersion(optionalMaxVersionStr, mustMaxVersionStr);
            int result2 = AppVersionUnit.compareVersion(appVersion, mustMaxVersionStr);
            int result3 = AppVersionUnit.compareVersion(appVersion, optionalMaxVersionStr);

            if(result1 > 0){
                if(result2 < 0){
                    //强制升级（可选）
                    appVersionResp = new AppVersionResp(optionalMaxVersion.getUrl(), optionalMaxVersion.getVersion(), optionalMaxVersion.getMd5(), optionalMaxVersion.getDescription(), (byte) 2);
                }else if(result2 == 0){
                    //可选
                    appVersionResp = new AppVersionResp(optionalMaxVersion.getUrl(), optionalMaxVersion.getVersion(), optionalMaxVersion.getMd5(), optionalMaxVersion.getDescription(), (byte) 1);
                }else {
                    if(result3 < 0){
                        //可选
                        appVersionResp = new AppVersionResp(optionalMaxVersion.getUrl(), optionalMaxVersion.getVersion(), optionalMaxVersion.getMd5(), optionalMaxVersion.getDescription(), (byte) 1);
                    }else{
                        //已经是最新
                        return ResponseData.fail(CodeIdEnum.UPDATED_VERSION);
                    }
                }
            }else {
                if(result2 < 0){
                    //强制升级
                    appVersionResp = new AppVersionResp(mustMaxVersion.getUrl(), mustMaxVersion.getVersion(), mustMaxVersion.getMd5(), mustMaxVersion.getDescription(), (byte) 2);
                } else{
                    //已经是最新
                    return ResponseData.fail(CodeIdEnum.UPDATED_VERSION);
                }
            }
        }else if(ObjectUtils.isEmpty(optionalMaxVersion) && !ObjectUtils.isEmpty(mustMaxVersion)){
            String mustMaxVersionStr = mustMaxVersion.getVersion();
            int result = AppVersionUnit.compareVersion(appVersion, mustMaxVersionStr);
            if(result >= 0){
                //最新
                return ResponseData.fail(CodeIdEnum.UPDATED_VERSION);
            } else{
                appVersionResp = new AppVersionResp(mustMaxVersion.getUrl(), mustMaxVersion.getVersion(), mustMaxVersion.getMd5(), mustMaxVersion.getDescription(), (byte) 2);
            }
        } else if(!ObjectUtils.isEmpty(optionalMaxVersion) && ObjectUtils.isEmpty(mustMaxVersion)){
            String optionalMaxVersionStr = optionalMaxVersion.getVersion();
            int result = AppVersionUnit.compareVersion(appVersion, optionalMaxVersionStr);
            if(result >= 0){
                //最新
                return ResponseData.fail(CodeIdEnum.UPDATED_VERSION);
            } else {
                appVersionResp = new AppVersionResp(optionalMaxVersion.getUrl(), optionalMaxVersion.getVersion(), optionalMaxVersion.getMd5(), optionalMaxVersion.getDescription(), (byte) 1);
            }
        } else{
            return ResponseData.fail("版本库中没有任何版本信息");
        }

        return ResponseData.success(appVersionResp);
    }



    @Override
    public SysAppVersion selectById(Long id) {
        return sysAppVersionMapper.selectByPrimaryKey(id);
    }
}
